package com.software.digitaltwin.tcp;

import java.io.IOException;
import java.net.Socket;

public class TCPConnection {
    private Socket socket;

    public TCPConnection(String address, int port) throws IOException{
        socket = new Socket(address, port);
        socket.setKeepAlive(true);
    }

    public void startBelt(byte num, byte speed) throws IOException {
        byte[] command = new byte[]{1, num, speed, 0, 0, 0, 0, 0};
        socket.getOutputStream().write(command);
    }

    public void stopBelt(byte num) throws IOException {
        byte[] command = new byte[]{2, num, 0, 0, 0, 0, 0, 0};

        socket.getOutputStream().write(command);
    }

    public void push(byte num, byte hold) throws IOException {
        byte[] command = new byte[]{3, num, 1, hold, 0, 0, 0, 0};

        socket.getOutputStream().write(command);
    }

    public byte[] getCurrentInfo() throws IOException {
        byte[] command = new byte[]{4, 0, 0, 0, 0, 0, 0, 0};

        socket.getOutputStream().write(command);

        return getMachineReport();
    }

    public byte[] getMachineReport() throws IOException{
        byte[] report = new byte[8];

        socket.getInputStream().read(report);
        return report;
    }

    public boolean isConnected() {
        try {
            socket.sendUrgentData(0xFF); //发送心跳包
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}

